var SplitPane = Class.create({
	initialize: function(surface, options)
	{
		if(!window.console || !window.console.log)
		{
			window.console = {
				log: function() {}
			};
		}
		
		this.surface = $(surface);
		
		if(!this.surface)
		{
			console.log("SplitPane: Invalid surface provided");
			return;
		}
		
		this.options = Object.extend({
			min_width: 300
		}, options);
		
		// For all but the last element add a drag handle
		for(var i=0; i<this.surface.childElements().length-1; i++)
		{
			var elem = this.surface.childElements()[i];
			var handle = Builder.node('div', {className: 'draghandle'});
			elem.insert(handle);
			elem.setStyle({position: 'relative'});
			new Draggable(handle, { 
					constraint: 'horizontal', 
					handle: 'draghandle',
					onStart: function(drag_object, event) {
						var lhs = drag_object.element.up();
						var rhs = lhs.next();
						
						this.start_position = event.clientX;
						this.lhs_start_width = lhs.getWidth();
						this.rhs_start_width = rhs.getWidth();
					}.bind(this),
					onDrag: function(drag_object, event) {
						var lhs = drag_object.element.up();
						var rhs = lhs.next();
						var delta = event.clientX - this.start_position;
						
						var new_lhs_width = this.lhs_start_width+delta;
						var new_rhs_width = this.rhs_start_width-delta;
						
						if(new_lhs_width < this.options.min_width || new_rhs_width < this.options.min_width)
							return;
						
						lhs.setStyle({width: new_lhs_width+'px'});
						rhs.setStyle({width: new_rhs_width+'px'});
					}.bind(this),
					onEnd: function(drag_object, event) {
						drag_object.element.setStyle({position: 'absolute', right: '0', left: 'auto', zIndex: '100'});
					}
				});
		}
		
		document.observe('resize', this.resize.bindAsEventListener(this));
	},
	
	resize: function(event)
	{
		var total_width = 0;
		var child_percentages = new Array();
		this.surface.childElements().each(function(elem){
			total_width += elem.getWidth();
		});
		
		var i = 0;
		this.surface.childElements().each(function(elem){
			child_percentages[i++] = (elem.getWidth() / total_width);
		});
		
		var new_width = this.surface.getWidth();
		var i = 0;
		this.surface.childElements().each(function(elem){
			var percentage = child_percentages[i++];
			elem.setStyle({width: (new_width*percentage)+'px'});
		});
	}
});

document.observe('dom:loaded', function(){
	$$('.splitpane').each(function(elem){
		new SplitPane(elem);
	});
});